package com.gyt.manager.common.constant;

import com.google.common.base.Splitter;
import com.google.common.collect.Sets;
import com.gyt.manager.common.dto.SysConfigDTO;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.regex.Pattern;

/**
 * @author gyt on 2021/4/30 13:36
 */
public class Base {

    private static final String SEMICOLON = ";";
    private static final String DESC = "DESC";
    private static final String ASC = "ASC";
    private static final Pattern SPLIT_PATTERN = Pattern.compile(",|;");

    /**
     * 校验排序.
     *
     * @param sort
     * @return boolean
     */
    public static Boolean checkSort(final String sort) {
        if (DESC.equals(sort)) {
            return true;
        } else if (ASC.equals(sort)) {
            return true;
        }
        return false;
    }

    /**
     * 解析字符串。
     *
     * @param val
     * @return list
     */
    public static Set<String> parseStrToSets(final String val) {
        List<String> list = parseStrToList(val);
        return Sets.newHashSet(list);
    }

    /**
     * 校验白名单.
     *
     * @param notifier
     * @param sysConfigDTO
     * @return
     */
    public static Set<String> checkWhite(final String notifier, final SysConfigDTO sysConfigDTO) {
        Set<String> users = Sets.newHashSet();
        List<String> alarmUsers = parseStrToList(notifier);
        if (CollectionUtils.isNotEmpty(alarmUsers)) {
            if (sysConfigDTO == null || StringUtils.isEmpty(sysConfigDTO.getValue())) {
                users = Sets.newHashSet(alarmUsers);
            } else {
                String whiteUsers = sysConfigDTO.getValue();
                List<String> whiteList = parseStrToList(whiteUsers);
                for (String white : whiteList) {
                    if (alarmUsers.contains(white)) {
                        users.add(white);
                    }
                }
            }
        }
        return users;
    }

    /**
     * 解析字符串。
     *
     * @param val
     * @return
     */
    private static List<String> parseStrToList(final String val) {
        return Splitter.on(SPLIT_PATTERN).omitEmptyStrings().trimResults()
                .splitToList(Optional.ofNullable(val).orElse(""));
    }
}
